package com.farmpost.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.farmpost.server.config.security.JwtTokenUtil;
import com.farmpost.server.controller.entity.ResetPassWord;
import com.farmpost.server.mapper.StuCertificationMapper;
import com.farmpost.server.mapper.UserInfoMapper;
import com.farmpost.server.pojo.RespBean;
import com.farmpost.server.pojo.StuCertification;
import com.farmpost.server.pojo.UserInfo;
import com.farmpost.server.service.IUserInfoService;
import com.farmpost.server.utils.Files;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author king
 * @since 2022-04-03
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private StuCertificationMapper stuCertificationMapper;
    @Autowired
    private Files files;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 登录之后返回token
     *
     * @param username
     * @param userPassword
     * @param code
     * @param request
     * @return
     */
    @Override
    public RespBean login(String username, String userPassword, String code, HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)) {
            return RespBean.error("验证码错误，请刷新重新输入");
        }
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        UserInfo userInfo = (UserInfo)userDetails;
        if (userDetails == null || userInfo.getUserLogout() == 1) {
            return RespBean.error("用户不存在或账号已注销或已被禁用，请先注册或联系管理员");
        }
        if (!passwordEncoder.matches(userPassword, userDetails.getPassword())) {
            return RespBean.error("用户名或密码错误");
        }
        if (!userDetails.isEnabled()) {
            return RespBean.error("用户账号被禁用，请联系管理员");
        }
        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return RespBean.success("登录成功", tokenMap);
    }

    /**
     * 根据用户名获取用户信息
     *
     * @param username
     * @return
     */
    @Override
    public UserInfo getUserInfoByUserName(String username) {

        return userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("username", username).eq("enable", 0).eq("user_logout",0));
    }

    /**
     * 用户进行注册
     *
     * @param username
     * @param userPassword
     * @param code
     * @param request
     * @return
     */
    @Override
    public RespBean registerUser(String username, String userPassword, String code, HttpServletRequest request) {
        //判断验证码
        String captcha = (String) request.getSession().getAttribute("captcha");
        if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(captcha)) {
            return RespBean.error("验证码错误，请刷新重新输入");
        }
        //判断用户名是否重复
        UserInfo userInfo = getUserNameOnRegister(username);
        if (userInfo == null) {
            //进行注册
            int userId = (int) (Math.random() * 1000000000);
            UserInfo info = new UserInfo();
            info.setUserId(userId);
            info.setUsername(username);
            info.setUserPassword(passwordEncoder.encode(userPassword));
            info.setCreateDate(LocalDate.now());
            int i = userInfoMapper.insert(info);
            System.out.println(i);
            if (i == 1)
                return RespBean.success("用户注册成功");
            else
                return RespBean.error("用户注册失败");
        } else
            return RespBean.error("用户名已被注册，请重新输入");

    }

    /**
     * 注册时根据用户名获取用户信息
     *
     * @param username
     * @return
     */
    @Override
    public UserInfo getUserNameOnRegister(String username) {
        return userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("username", username));
    }

    /**
     * 修改用户信息
     * @param username
     * @param sex
     * @param age
     * @return
     */
    @Override
    public RespBean updateUserInfo(String username, String sex, int age, String other) {
        UserInfo user = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        StuCertification stuCertification = stuCertificationMapper.selectOne(new QueryWrapper<StuCertification>().eq("user_id", user.getUserId()));
        if (stuCertification == null) {
            //用户未学生认证
            int updateUserInfo = userInfoMapper.updateUserInfo(username, sex, age, user.getUserId(), other);
            if (updateUserInfo == 1)
                return RespBean.success("用户修改成功");
            else
                return RespBean.error("用户修改失败");
        }else {
            //经过认证，通过自定义sql修改用户信息
            int userInfoStu = userInfoMapper.updateUserInfoStu(username, true, stuCertification.getStuId(), sex, age, other, user.getUserId());
            if (userInfoStu == 1)
                return RespBean.success("用户认证过且修改信息成功");
            else
                return RespBean.error("用户认证修改信息失败");
        }
    }

    /**
     * 根据用户id查询用户信息
     * @param userId
     * @return
     */
    @Override
    public UserInfo getUserInfoByUserId(Integer userId) {
        return userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("user_id",userId).eq("enable",0).eq("user_logout",0));
    }

    /**
     * 用户头像上传
     * @param file
     * @return
     */
    @Override
    public RespBean uploadUserFace(MultipartFile file) throws Exception {
        if (file.isEmpty())
            return RespBean.error("文件为空！请重新选择文件");
        String filename = files.upload(file);
        String url = ResourceUtils.getFile("classpath:") + "\\static\\image\\" + filename;
        HashMap<String, Object> hashMap = new HashMap<>();
        //将路径存入数据库
        int updateURL = userInfoMapper.updateURL(url, ((UserInfo) (SecurityContextHolder.getContext().getAuthentication().getPrincipal())).getUserId());
        if (updateURL == 1) {
            hashMap.put("msg","头像上传成功");
            hashMap.put("url",url);
            return RespBean.success("头像上传成功",hashMap);
        }else {
            hashMap.put("msg", "头像上传失败");
            hashMap.put("url", url);
            return RespBean.success("头像上传成功", hashMap);
        }
    }

    /**
     * 账号注销
     * @return
     */
    @Override
    public RespBean quitSys() {
        UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (userInfo.getUserId() == null)
            return RespBean.error("当前账号未登录，请先登录");
        int quitSys = userInfoMapper.quitSys(userInfo.getUserId());
        if (quitSys == 1)
            return RespBean.success("注销成功");
        return RespBean.error("注销失败");
    }

    /**
     * 修改密码
     * @param resetPassWord
     * @return
     */
    @Override
    public RespBean modifyPassWord(ResetPassWord resetPassWord) {
        UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserInfo userInfoByUserName = getUserInfoByUserName(userInfo.getUsername());
        if (!passwordEncoder.matches(resetPassWord.getOldPassWord(),userInfoByUserName.getPassword())) {
            return RespBean.error("原密码输入错误");
        }
        if (passwordEncoder.matches(resetPassWord.getNewPassWord(),userInfoByUserName.getPassword())) {
            return RespBean.error("修改后的密码与原密码一致，请重新输入");
        }
        UserInfo info = new UserInfo();
        info.setUserPassword(passwordEncoder.encode(resetPassWord.getNewPassWord()));
        int update = userInfoMapper.update(info, new QueryWrapper<UserInfo>().eq("user_id", userInfo.getUserId()));
        if (update >= 1)
            return RespBean.success("修改密码成功");
        return RespBean.error("修改密码失败");
    }
}
